<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/8/8
  Time: 20:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page import="java.awt.*" %>
<%@ page import="java.util.Random" %>
<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="javax.imageio.ImageIO" %>
<%@ page contentType="image/jpeg;charset=UTF-8" language="java" %>
<%!
    //随机产生颜色值
    public Color getColor(){
        Random random = new Random();
        int r = random.nextInt(256);
        int g = random.nextInt(256);
        int b = random.nextInt(256);
        return new Color(r,g,b);
    }

    public String getNum(){
        int random = (int) (Math.random()*9000) + 1000;
        return String.valueOf(random);
    }

%>

<%
    //禁止缓存，防止验证码过期
    response.setHeader("Pragma","no-cache");
    response.setHeader("Cache-Control","no-cache");
    response.setHeader("Expires","0");

    //绘制验证码
    BufferedImage image = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
    //画笔
    Graphics graphics = image.getGraphics();
    graphics.fillRect(0,0,80,30);
    //绘制干扰线条
    for(int i=0;i<60;i++){
        Random random = new Random();
        int xBegin = random.nextInt(80);
        int yBegin = random.nextInt(30);
        int xEnd = random.nextInt(xBegin + 10);
        int yEnd = random.nextInt(yBegin + 10);
        graphics.setColor(getColor());
        //绘制线条
        graphics.drawLine(xBegin,yBegin,xEnd,yEnd);
    }

    graphics.setColor(Color.BLACK);
    String checkCode = getNum();
    StringBuilder sb = new StringBuilder();
    for(int i=0;i<checkCode.length();i++){
        sb.append(checkCode.charAt(i) + " ");//验证码的每一位数字
    }
    graphics.setFont(new Font("seif",Font.BOLD,20));
    graphics.drawString(sb.toString(),15,20);//绘制验证码
    //将验证码真实值保存在session中，供使用时比较真实性
    session.setAttribute("CHECKCODE",checkCode);

    //真实的产生图片
    ImageIO.write(image,"jpeg",response.getOutputStream());

    //关闭
    out.clear();
    out = pageContext.pushBody();//<img src="xxx">将图片放置到src中

%>
